package com.xdy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdy.reggie.common.R;
import com.xdy.reggie.entity.Category;
import com.xdy.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功！");
    }

    @GetMapping("/page")
    public R<Page<Category>> page(int page,int pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> deleteById(@RequestParam("ids") Long id){
        log.info("删除分类id ===> {}",id);
//        categoryService.removeById(id);删除分类应该先检查该分类下是否存在菜品
        categoryService.remove(id);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<Category>> getListByType(Category category){
        log.info("type ===> {}",category.getType());
        List<Category> categoryList = null;
        if(category.getType() != null){
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Category::getType,category.getType());
            queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
            categoryList = categoryService.list(queryWrapper);
        }else{
            categoryList = categoryService.list();
        }
        return R.success(categoryList);
    }
}
